﻿//------------------------------------------------------------------------------
// @Class name: Cryptor
// @Description: Cryptor class is used to encrypt and decrypt with Md5Hash
// @Author: Nguyen Thanh Hoang
// @History: 
//  - Created: 2013/07/22
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace CryptorLib
{
    public class Cryptor
    {
        static public string Key { get; set;}

        static public string Encrypt(string strOriginalString)
        {
            byte[] EncryptedArray;
            byte[] Buffer = Encoding.ASCII.GetBytes(strOriginalString);

            MD5 md5Hash = MD5.Create();
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

            DES.Key = md5Hash.ComputeHash(Encoding.ASCII.GetBytes(Key));
            DES.Mode = CipherMode.ECB;

            EncryptedArray = DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length);

            //Clear md5Hash
            md5Hash.Clear();
            DES.Clear();

            return Convert.ToBase64String(EncryptedArray);
        }

        static public string Decrypt(string strEncryptedString)
        {
            byte[] Buffer = Convert.FromBase64String(strEncryptedString);
            byte[] DecryptedArray;

            MD5 md5Hash = MD5.Create(); 
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

            DES.Key = md5Hash.ComputeHash(Encoding.ASCII.GetBytes(Key));
            DES.Mode = CipherMode.ECB;

            DecryptedArray = DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length);

            //Clear md5Hash
            md5Hash.Clear();
            DES.Clear();

            return Encoding.ASCII.GetString(DecryptedArray);
        }
    }
}
